# -*- coding: utf-8 -*-

from . import auth
from flask import render_template, redirect, request, url_for, \
    flash, jsonify, current_app, session
from ..models import User
from .. import db
from .forms import LoginForm, ChangePasswordForm
from flask_login import login_user, logout_user, current_user
from datetime import datetime, timedelta


@auth.before_app_request
def before_request():
    if current_user.is_authenticated:
        current_user.ping()


@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.is_submitted():
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            return redirect(request.args.get('next') or url_for('main.index'))
        flash(u'用户名或者密码错误')
    return render_template('auth/login.html', form=form)


@auth.route('/logout')
def logout():
    # Remove the user information from the session
    logout_user()
    return redirect(url_for('auth.login'))


@auth.route('/changePassword', methods=['POST'])
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.old_password.data):
            current_user.password = form.new_password.data
            db.session.add(current_user)
            return jsonify({'result': 'success', 'message': u'密码更改成功！'})
        else:
            return jsonify({'result': 'false', 'message': u'密码错误！'})
    return jsonify({'result': 'false', 'message': u'验证不通过！'})


@auth.route('/role')
def role_manage():
    return render_template('auth/role.html', title=u'角色管理|CMDB运维平台',
                           member='active', role_active='active')